import React, { PureComponent } from 'react';
import { Input, Tooltip, Tag, Icon, message } from 'antd';

class ColorSpec extends PureComponent {
  state = {
    inputVisible: false,
    inputValue: '',
  };

  render() {
    const { inputVisible, inputValue } = this.state;
    const { value, onChange } = this.props;

    const saveInputRef = input => {
      this.input = input;
    };

    const showInput = () => {
      this.setState({ inputVisible: true }, () => this.input.focus());
    };

    const handleInputChange = e => {
      this.setState({ inputValue: e.target.value });
    };

    const handleInputAdd = () => {
      const index = value.indexOf(inputValue);
      if (index === -1) {
        const newValue = [...value];
        newValue.push(inputValue);
        onChange(newValue);
        this.setState({ inputVisible: false, inputValue: '' });
      } else {
        message.info('已存在相同的颜色');
      }
    };

    const handleTagClose = index => {
      const newValue = [...value];
      newValue.splice(index, 1);
      onChange(newValue);
    };

    return (
      <div>
        {value.map((tag, index) => {
          const isLongTag = tag.length > 20;
          const tagElem = (
            <Tag key={tag} closable afterClose={() => handleTagClose(index)}>
              {isLongTag ? `${tag.slice(0, 20)}...` : tag}
            </Tag>
          );
          return isLongTag ? (
            <Tooltip title={tag} key={tag.id}>
              {tagElem}
            </Tooltip>
          ) : (
            tagElem
          );
        })}
        {inputVisible && (
          <Input
            ref={saveInputRef}
            type="text"
            size="small"
            style={{ width: 78 }}
            value={inputValue}
            onChange={handleInputChange}
            onBlur={handleInputAdd}
            onPressEnter={handleInputAdd}
          />
        )}
        {!inputVisible && (
          <Tag onClick={() => showInput()} style={{ background: '#fff', borderStyle: 'dashed' }}>
            <Icon type="plus" /> 新增
          </Tag>
        )}
      </div>
    );
  }
}

export default ColorSpec;
